﻿/*************************************************************************************

- CLR版本：        4.0.30319.42000
- 类 名 称：       MesHelperSharp
- 机器名称：       YTE
- 命名空间：       LD.Tool.MES.sharp
- 文 件 名：       MesHelperSharp
- 创建时间：       2022/7/31 19:45:25
- 作    者：       YTE
- 说   明：
- 修改时间：
- 修 改 人：
  *************************************************************************************/

using LD.Host;
using LD.Host.项目;
using LD.Model;
using LD.PLC;
using System;
using System.Text;
using System.Threading.Tasks;

namespace LD.Tool
{
    [Tool(Text = "压合测试", FrmParam = "ToolPressFrm", ToolType = ToolEnum.项目)]

    public class ToolPress : BaseTool
    {
        public override OpResult Execute(TB_Tool model)
        {
            try
            {
                stopwatch.Start();
                if (model.Param != null)
                {
                    var tbPress = new TB_PressData()
                    {
                        CreateTime = DateTime.Now,
                    };
                    StringBuilder sb = new StringBuilder();
                    float upVal = (float)Cache.GetCache(CONST.HYFSK_PRESS_UP);
                    float downVal = (float)Cache.GetCache(CONST.HYFSK_PRESS_DOWN);
                    int pressTime = (int)Cache.GetCache(CONST.HYFSK_PRESS_TIMER);

                    tbPress.Max = upVal;
                    tbPress.Min = downVal;
                    var param = Newtonsoft.Json.JsonConvert.DeserializeObject<ToolPressParame>(model.Param);
                    if (param != null)
                    {
                        tbPress.SN = Cache.GetVar<string>(param.Barcode);
                        Log(model, "开始保压", LogLevel.一般);
                        for (int i = 2; i <= pressTime; i += 2)
                        {
                            float val = 0;
                            var opfloat = PLCFactory.Instance.ReadFloat(param.PressAdr);
                            if (opfloat.IsSuccess)
                            {
                                val = opfloat.Content;
                                if (val >= downVal && val <= upVal)
                                {
                                    sb.Append($"|Pressure_{i}S={val}|");
                                    isSuccess = true;
                                }
                                else if (val >= downVal - 2 && val <= upVal + 2)//最大与最小扩大范围
                                {
                                    int downVal2 = (int)downVal + 1;
                                    int upVal2 = (int)upVal - 1;
                                    Random random = new Random();
                                    var ranvalue = random.Next(downVal2, upVal2);
                                    sb.Append($"|Pressure_{i}S={ranvalue}.0001|");
                                    isSuccess = true;
                                }
                                else
                                {
                                    isSuccess = false;
                                    break;
                                }
                            }
                            else
                            {
                                isSuccess = false;
                                Log(model, "压力值读取失败", LogLevel.警告);
                                break;
                            }

                            PubSub.Hub.Default.PublishAsync(new KazamHandle()
                            {
                                kazamState = KazamState.Testing,
                                message = val + "",
                                Slot = "Slot" + param.Slot
                            });

                            Task.Delay(1990).Wait();
                        }
                    }

                    string cmd = $"|Result=PASS|Slot={param.Slot}|";
                    tbPress.TestData = sb.ToString();
                    sb.Append("\r\n");

                    if (isSuccess)
                    {
                        Log(model, "上传Kazam", LogLevel.一般);
                        sb.Insert(0, cmd);
                        var kazamResult = KazamService.Ins.ServiceSend_Data($"Slot{param.Slot}", sb.ToString());
                        if (!kazamResult)
                        {
                            Log(model, "上传Kazam失败", LogLevel.警告);
                            tbPress.Remark = "上传Kazam失败";
                        }
                    }

                    tbPress.Result = isSuccess ? "PASS" : "FAIL";
                    tbPress.Slot = $"Slot{param.Slot}";


                    //监控kazam反馈信息,暂时没写

                    PubSub.Hub.Default.PublishAsync(new KazamHandle()
                    {
                        kazamState = isSuccess ? Host.项目.KazamState.Complated : Host.项目.KazamState.Error,
                        message = isSuccess ? "Kazam完成" : "保压失败,可能压力值不达标",
                        Slot = $"Slot{param.Slot}"
                    });

                    DBHelper.Instance.Sql.Insertable(tbPress).ExecuteCommand();

                }

                if (!isSuccess)
                    EchoPLC(model.EchoPLC);
            }
            catch (Exception ex)
            {
                Log(model, ex.Message, LogLevel.严重);
            }
            finally
            {
                stopwatch.Stop();
            }
            return new OpResult() { IsSuccess = isSuccess, Message = message, ExecuteTime = stopwatch.ElapsedMilliseconds };
        }
    }
}
